package com.xzakota.minesweeper.controller;

import com.xzakota.minesweeper.App;
import com.xzakota.minesweeper.model.Observable;
import com.xzakota.minesweeper.model.entity.LevelBean;
import com.xzakota.minesweeper.model.entity.RecordBean;

import java.io.*;

/**
 * 游戏记录管理器
 *
 * @author Xzakota
 */
public class GameRecords extends Observable {
    private static final File recordFile = createRecordFile();
    
    public RecordBean basicLevelRecord;
    public RecordBean intermediateLevelRecord;
    public RecordBean expenseLevelRecord;

    public GameRecords() {
        loadGameRecords();
    }

    private static File createRecordFile() {
        try {
            return new File(App.APP_DATA_DIR_PATH, "record");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void resetRecords() {
        basicLevelRecord = new RecordBean(LevelBean.ID_BASIC, "匿名", 999);
        intermediateLevelRecord = new RecordBean(LevelBean.ID_INTERMEDIATE, "匿名", 999);
        expenseLevelRecord = new RecordBean(LevelBean.ID_EXPENSE, "匿名", 999);
    }

    private void loadGameRecords() {
        try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(recordFile))) {
            basicLevelRecord = (RecordBean) in.readObject();
            intermediateLevelRecord = (RecordBean) in.readObject();
            expenseLevelRecord = (RecordBean) in.readObject();
        } catch (Exception e) {
            resetRecords();
        }
    }

    public void saveRecords() {
        try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(recordFile))) {
            out.writeObject(basicLevelRecord);
            out.writeObject(intermediateLevelRecord);
            out.writeObject(expenseLevelRecord);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void saveNewRecord(RecordBean record) {
        switch (record.levelID) {
            case LevelBean.ID_BASIC:
                basicLevelRecord = record;
                break;
            case LevelBean.ID_INTERMEDIATE:
                intermediateLevelRecord = record;
                break;
            case LevelBean.ID_EXPENSE:
                expenseLevelRecord = record;
                break;
        }
    }

    public RecordBean getGameRecordByLevelID(int id) {
        return switch (id) {
            case LevelBean.ID_BASIC -> basicLevelRecord;
            case LevelBean.ID_INTERMEDIATE -> intermediateLevelRecord;
            case LevelBean.ID_EXPENSE -> expenseLevelRecord;
            default -> null;
        };
    }
}
